package com.redwinter.logkit.support.service;

import com.redwinter.logkit.sdk.beans.LogResult;
import com.redwinter.logkit.sdk.service.LogRecordService;
import com.redwinter.logkit.sdk.util.JsonUtil;
import com.redwinter.logkit.support.api.LogCollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @author goudadong
 * @description 日志记录
 * @datetime 2021-12-15 22:33
 * @email 2360564660@qq.com
 **/
@Slf4j
@Service
public class LogRecordJsonService implements LogRecordService {

    private final Environment env;
    private final LogCollectService logCollectService;

    public LogRecordJsonService(Environment env, LogCollectService logCollectService) {
        this.env = env;
        this.logCollectService = logCollectService;
    }

    @Override
    public void apply(LogResult recordResult) {
        String moduleCode = env.getProperty("spring.application.name");
        String moduleName = env.getProperty("info.description");
        if (StringUtils.isEmpty(moduleName)) {
            moduleName = moduleCode;
        }
        recordResult.setModuleCode(moduleCode).setModuleName(moduleName);
        Object value = recordResult.getData();
        if (value instanceof ArrayList) {
            value = ((ArrayList<?>) value).get(0);
        }
        if (value instanceof Method) {
            value = value.toString();
        }
        recordResult.setData(value);
        String bizType = recordResult.getBizType();
        logCollectService.store(bizType, JsonUtil.toJson(recordResult));
    }
}
